package com.xyu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.xyu.common.to.SkuEsModel;
import com.xyu.gulimall.search.config.GulimallElasticsearchConfig;
import com.xyu.gulimall.search.contstant.EsContStant;
import com.xyu.gulimall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 商品上架到es
     * @param skuEsModels
     * @return
     * @throws IOException
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //报错到es
        //1，建立好索引 product 建立映射关系
        //2，批量报错到es中
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModel skuEsMode : skuEsModels) {
            //创建一个索引
            IndexRequest indexRequest = new IndexRequest(EsContStant.PRODUCT_INDEX);
            //添加id
            indexRequest.id(skuEsMode.getSkuId().toString());
            //添加保存数据
            String jsonString = JSON.toJSONString(skuEsMode);
            //以JSON类型保存
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
        //获取批量操作是否成功
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.error("商品上架错误" + collect);
        System.out.println("b\t" + b);
        return b;
    }
}
